//
//  WKBookSelectPhotoCell.m
//  WKMaybell
//
//  Created by 何文虎 on 2018/12/17.
//  Copyright © 2018 何文虎. All rights reserved.
//

#import "WKBookSelectPhotoCell.h"
@interface WKSelectPhotoCell : UICollectionViewCell
@property(nonatomic,strong)UIImageView *imgView;
@property(nonatomic,strong)UIImage *img;

@end

@implementation WKSelectPhotoCell

- (instancetype)initWithFrame:(CGRect)frame{
    if (self == [super initWithFrame:frame]) {
        self.imgView = [[UIImageView alloc]initWithFrame:self.contentView.bounds];
        [self.contentView addSubview:self.imgView];
        self.layer.cornerRadius = 5;
        self.layer.masksToBounds = YES;
        self.imgView.layer.cornerRadius = 5;
        self.imgView.layer.masksToBounds = YES;
        self.imgView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return self;
}

-(void)setImg:(UIImage *)img{
    _img = img;
    self.imgView.image = img;
}

@end


@interface WKBookSelectPhotoCell () <UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property(nonatomic,strong)UILabel *titleLb;
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *imgArr;
@property (nonatomic, strong) NSMutableArray<PHAsset *> *selectAssets;
@end

@implementation WKBookSelectPhotoCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self == [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setup];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setup{
    
    

    
}

- (void)initCollctionView{
    
    CGFloat height = 0;
    CGFloat itemHeigth = (ScreenWidth - 24 -10)/3;
    if (self.imgArr.count>=3 && self.imgArr.count<6) {
        
        height =  itemHeigth*2+10+5;
    }else if(self.imgArr.count>=6){
        height = itemHeigth*3+10+5*2;
    }else{
        height = itemHeigth + 10;
    }
    
  
    
    CGFloat width = (ScreenWidth-10-24)/3;
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(width-1, width-1);
    layout.minimumLineSpacing = 5;
    layout.minimumInteritemSpacing = 5;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.sectionInset = UIEdgeInsetsMake(0, 12, 0, 12);
    layout.sectionHeadersPinToVisibleBounds = NO;
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,40,ScreenWidth,height) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:self.collectionView];
    
    [self.collectionView registerClass:[WKSelectPhotoCell class] forCellWithReuseIdentifier:NSStringFromClass([WKSelectPhotoCell class])];
    
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    
    _collectionView.layer.masksToBounds = YES;
    
    [self setUpLongPressGes];
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
  NSInteger count =  self.imgArr.count<9 ?  self.imgArr.count+1 : self.imgArr.count;
    return count;
}

- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    WKSelectPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([WKSelectPhotoCell class]) forIndexPath:indexPath];
    cell.backgroundColor = [UIColor magentaColor];
    if(indexPath.row<self.imgArr.count){
     cell.img = self.imgArr[indexPath.row];
    }
    
    return cell;
}

- (void)displayImgWithImgArr:(NSArray*)imgs{
    
    self.imgArr = imgs.mutableCopy;
    
    [self.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview) withObject:nil];
    [self initCollctionView];
    
//    [self.collectionView reloadData];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ZLPhotoActionSheet *ac = [[ZLPhotoActionSheet alloc] init];
    ac.configuration.maxSelectCount = 9;
    ac.configuration.maxPreviewCount = 10;
    ac.sender = [WHUtiities getCurrentTopViewController];
    ac.configuration.allowSelectVideo = NO;
    ac.configuration.allowSelectImage = YES;
    
//    ac.configuration.allowEditVideo = NO;
//    ac.configuration.maxVideoDuration = 10;
    
    if (indexPath.row==self.imgArr.count || self.imgArr.count<=0) {
    //选择回调
        @weakify(self);
    [ac setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        @strongify(self);
        [self.imgArr addObjectsFromArray:images];
        [self.selectAssets addObjectsFromArray:assets];
        if (self.selectImgBlock) {
            self.selectImgBlock(self.imgArr);
        }
        [collectionView reloadData];
        
    }];
    
    //调用相册
    [ac showPreviewAnimated:YES];
    
//    //预览网络图片
//    [ac previewPhotos:arrNetImages index:0 hideToolBar:YES complete:^(NSArray * _Nonnull photos) {
//        //your codes
//    }];
        
        
    
    }else{
    
    [ac previewSelectedPhotos:self.imgArr assets:self.selectAssets index:indexPath.row isOriginal:YES];
        
    }
}




#pragma mark - 添加长按手势
- (void)setUpLongPressGes {
    UILongPressGestureRecognizer *longPresssGes = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressMethod:)];
    [self.collectionView addGestureRecognizer:longPresssGes];
}

- (void)longPressMethod:(UILongPressGestureRecognizer *)longPressGes {
    
    // 判断手势状态
    switch (longPressGes.state) {
            
        case UIGestureRecognizerStateBegan: {
            
            // 判断手势落点位置是否在路径上(长按cell时,显示对应cell的位置,如path = 1 - 0,即表示长按的是第1组第0个cell). 点击除了cell的其他地方皆显示为null
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPressGes locationInView:self.collectionView]];
            // 如果点击的位置不是cell,break
            if (nil == indexPath) {
                break;
            }
            NSLog(@"%@",indexPath);
            // 在路径上则开始移动该路径上的cell
            [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
        }
            break;
            
        case UIGestureRecognizerStateChanged:
            // 移动过程当中随时更新cell位置
            [self.collectionView updateInteractiveMovementTargetPosition:[longPressGes locationInView:self.collectionView]];
            break;
            
        case UIGestureRecognizerStateEnded:
            // 移动结束后关闭cell移动
            [self.collectionView endInteractiveMovement];
            break;
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}

// 在开始移动时会调用此代理方法，
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
     if (indexPath.row==self.imgArr.count || self.imgArr.count<=0) {
         return NO;
     }
    return YES;
}


- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    

    //取出源item数据
    id objc = [self.imgArr objectAtIndex:sourceIndexPath.item];
    //从资源数组中移除该数据
    [self.imgArr removeObject:objc];
    //将数据插入到资源数组中的目标位置上
    [self.imgArr insertObject:objc atIndex:destinationIndexPath.item];
    
}

- (NSMutableArray*)imgArr{
    if (!_imgArr) {
        _imgArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _imgArr;
}

- (NSMutableArray*)selectAssets{
    if (!_selectAssets) {
        _selectAssets = [NSMutableArray array];
    }
    return _selectAssets;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
